package com.example.security.authentication;

import java.io.IOException;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
/**
 * @className: TenantFilter
 * @author: YTF
 * @date: 2025/4/30 21:25
 * @description: 假设您想要添加一个Filter获取租户 ID 标头并检查当前用户是否有权访问该租户
 */
public class TenantFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String tenantId = request.getHeader("X-Tenant-Id"); //(1)
        boolean hasAccess = isUserAllowed(tenantId); //(2)
        if (hasAccess) {
            filterChain.doFilter(request, response); //(3)
            return;
        }
        throw new AccessDeniedException("Access denied"); //(4)
    }

    private boolean isUserAllowed(String tenantId) {
        return true;
    }

}